# Darren
# 2025年02月24日11时14分20秒
import copy


# 浅拷贝：对象的顶层拷贝
def use_copy():
    a = [12, 22]
    b = [33, 44]
    c = [a, b]
    d = copy.copy(c)  # 仅第一层拷贝，即[a,b]
    print(f"id(c)={id(c)},id(d)={id(d)}")
    print(f"id(c[0])={id(c[0])},id(c[1])={id(c[1])}")  # id(c[0])==id(d[0})==id(a)
    print(f"id(d[0])={id(d[0])},id(d[1])={id(d[1])}")  # id(c[1])==id(c[2])==id(b)
    print(d)
    a[0] = 50
    print(d)


# 深拷贝：深拷贝是对于一个对象所有层次的拷贝(递归)
def use_deepcopy():
    a = [12, 22]
    b = [33, 44]
    c = [a, b]
    d = copy.deepcopy(c)
    print(f"id(c)={id(c)},id(d)={id(d)}")
    print(f"id(c[0])={id(c[0])},id(c[1])={id(c[1])}")
    print(f"id(d[0])={id(d[0])},id(d[1])={id(d[1])}")
    print(d)
    # id(c[1])==id(c[2])==id(b)    print(d)

# 对象的深拷贝，浅拷贝
class Gun:

    def __init__(self, model):
        # 枪的型号
        self.model = model
        # 子弹数量
        self.bullet_count = 0

    def add_bullet(self, count):
        self.bullet_count += count

    def shoot(self):
        # 判断是否还有子弹
        if self.bullet_count <= 0:
            print("没有子弹了...")

            return

        # 发射一颗子弹
        self.bullet_count -= 1

        print("%s 发射子弹[%d]..." % (self.model, self.bullet_count))


class Soldier:

    def __init__(self, name):
        # 1. 姓名
        self.name = name

        # 2. 枪 - 新兵没有枪
        self.gun = None

    def fire(self):
        # 1. 判断士兵是否有枪
        # if self.gun == None:
        if self.gun is None:
            print("[%s] 还没有枪..." % self.name)

            return

        # 2. 高喊口号
        print("冲啊...[%s]" % self.name)

        # 3. 让枪装填子弹
        self.gun.add_bullet(50)

        # 4. 让枪发射子弹
        self.gun.shoot()


if __name__ == '__main__':
    use_copy()
    print('-' * 50)
    use_deepcopy()
    print('-' * 50)
    gun = Gun('AK47')
    xusanduo = Soldier('许三多')
    xusanduo.gun = gun  # 捡枪
    xu2=copy.copy(xusanduo)
    xu3=copy.deepcopy(xusanduo)
    xusanduo.fire()
    print(xu2.gun.bullet_count)  # 只拷贝士兵对象，属性枪的对象未copy
    print(xu3.gun.bullet_count)  # 深拷贝，copy枪初始化弹夹子弹为0

